package com.pangolin.pangolinim.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.sqlite.DBContact;
import com.pangolin.pangolinim.sqlite.DBMessage;
import com.pangolin.pangolinim.sqlite.DBSession;
import com.pangolin.pangolinim.sqlite.DBUser;
import com.pangolin.pangolinim.sqlite.DbHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBHelperUtil {
    private static String dbname;
    private static int version;
    private static DbHelper dbHelper;
    private static Context context;
    private static DBHelperUtil instance;

    /**
     * TODO:打开数据库，该函数必须调用在getInstance之前
     * @param c 上下文Context
     * @param db 数据库名称
     * @param ver 数据库版本
     */
    public static void OpenDB(Context c , String db , int ver){
        dbname = db;
        version = ver;
        context = c;
        dbHelper = new DbHelper(context , dbname , null , version);
    }

    /**
     * TODO：关闭数据库
     */
    public static void close(){
        if(dbHelper != null){
            dbHelper.close();
            dbHelper = null;
        }
    }

    /**
     * TODO：获取DBHelperUtil类实例（单例），所有操作都需要通过该函数获取实例
     * @return DBHelperUtil类实例
     */
    public static DBHelperUtil getInstance(){
        if(instance==null){
            synchronized (DBHelperUtil.class){
                if(instance==null){
                    instance=new DBHelperUtil();
                }
            }
        }
        return instance;
    }

    /**
     * @chat_msg表
     * TODO:插入普通聊天消息
     * @param msg 消息内容类
     * @return  结果（true-成功；false-失败）
     */
    public static boolean insert_msg(DBMessage msg){
        if(dbHelper == null) return false;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db == null) return false;
        if(msg.getMid() == null || msg.getUid() <= 0) return false;
        ContentValues values = new ContentValues();
        values.put("mid" , msg.getMid());
        values.put("uid" , msg.getUid());
        if(msg.getType() > 0){ values.put("type",msg.getType()); }
        if(msg.getIo() > 0){ values.put("io" , msg.getIo()); }
        if(msg.getStatus() > 0){ values.put("status" , msg.getStatus()); }
        if(msg.getMsgtext() != null){ values.put("msgtext" , msg.getMsgtext()); }
        if(msg.getTimestamp() > 0){ values.put("timestamp" , msg.getTimestamp()); }
        db.insert("chat_msg" , null , values);
        return true;
    }

    /**
     * TODO:清空用户聊天数据
     * @param uid   用户id
     * @return 结果（true-成功；false-失败）
     */
    public static boolean clear_msg(int uid){
        if(dbHelper == null) return false;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db == null) return false;
        if(uid <= 0) return false;
        db.delete("chat_msg" , "uid=?" ,new String[]{String.valueOf(uid)});    //如果有删除相关数据
        return true;
    }

    /**
     * TODO:倒序获取用户的聊天数据
     * @param uid 用于uid
     * @param start 开始序号（DESC）
     * @param limit 获取数量
     * @return  聊天记录列表
     */
    public static List<DBMessage> get_msgs(int uid , int start , int limit){
        if(dbHelper == null) return null;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        if(db == null) return null;
        //查询数据
        Cursor cursor = db.query(
                "chat_msg" ,
                new String[]{"mid","uid","type","io","status","timestamp","msgtext"} ,
                "uid=?" ,
                new String[]{String.valueOf(uid)} ,
                null ,
                null ,
                "timestamp DESC" ,
                String.valueOf(start)+","+String.valueOf(limit));
        if(cursor.moveToFirst()){
            List<DBMessage> messages = new ArrayList<DBMessage>();
            do {
                DBMessage message = new DBMessage();
                message.setMid(cursor.getString(0));
                message.setUid(cursor.getInt(1));
                message.setType(cursor.getInt(2));
                message.setIo(cursor.getInt(3));
                message.setStatus(cursor.getInt(4));
                message.setTimestamp(cursor.getInt(5));
                message.setMsgtext(cursor.getString(6));
                messages.add(message);
            }while (cursor.moveToNext());
            cursor.close();
            return messages;
        }
        cursor.close();
        return null;
    }

    /**
     * @chat_msg表
     * TODO:修改普通聊天消息的状态字段
     * @param msg  消息信息类
     * @return  结果（true-成功；false-失败）
     */
    public static boolean update_msg(DBMessage msg){
        if(dbHelper == null) return false;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db == null) return false;
        if(msg.getMid() == null) return false;
        ContentValues values = new ContentValues();
        values.put("mid" , msg.getMid());
        if(msg.getUid() > 0){ values.put("uid"  , msg.getUid()); }
        if(msg.getType() > 0){ values.put("type" , msg.getType()); }
        if(msg.getIo() > 0){ values.put("io" , msg.getIo());}
        if(msg.getStatus() > 0){ values.put("status" , msg.getStatus());}
        if(msg.getMsgtext() != null){ values.put("msgtext" , msg.getMsgtext());}
        db.update("chat_msg" ,  values , "mid=?" ,new String[]{String.valueOf(msg.getMid())});
        return true;
    }

    /**
     * @chat_user表
     * TODO:修改用户表
     * @param user 要修改的用户信息类
     * @return  结果（true-成功；false-失败）
     */
    public static boolean update_user(DBUser user){
        if(dbHelper == null) return false;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db == null) return false;
        if(user.getUid() <= 0) return false;
        ContentValues values = new ContentValues();
        if(user.getName() != null){ values.put("username" , user.getName());}
        if(user.getHeadimg() != null){ values.put("headimg" , user.getHeadimg());}
        if(user.getPubkeya() != null){ values.put("pubkeya" , user.getPubkeya()); }
        if(user.getPrikeya() != null){ values.put("prikeya" , user.getPrikeya()); }
        if(user.getPubkeyb() != null){ values.put("pubkeyb" , user.getPubkeyb()); }
        if(user.getPrikeyb() != null){ values.put("prikeyb" , user.getPrikeyb()); }
        if(user.getSeckey() != null){ values.put("seckey" , user.getSeckey()); }
        if(user.getType() > 0){ values.put("type" , user.getType()); }
        db.update("chat_user" ,  values , "uid=?" ,new String[]{String.valueOf(user.getUid())});
        return true;
    }

    /**
     * @chat_user表
     * TODO:插入用户数据到user表
     * @param user 用户信息类
     * @return   结果（true-成功；false-失败）
     */
    public static boolean insert_user(DBUser user){
        if(dbHelper == null) return false;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db == null) return false;
        if(user.getUid() <= 0) return false;
        db.delete("chat_user" , "uid=?" ,new String[]{String.valueOf(user.getUid())});    //如果有删除相关数据
        ContentValues values = new ContentValues();
        values.put("uid" , user.getUid());
        if(user.getName() != null){ values.put("username" , user.getName());}
        if(user.getHeadimg() != null){ values.put("headimg" , user.getHeadimg());}
        if(user.getPubkeya() != null){ values.put("pubkeya" , user.getPubkeya()); }
        if(user.getPrikeya() != null){ values.put("prikeya" , user.getPrikeya()); }
        if(user.getPubkeyb() != null){ values.put("pubkeyb" , user.getPubkeyb()); }
        if(user.getPrikeyb() != null){ values.put("prikeyb" , user.getPrikeyb()); }
        if(user.getSeckey() != null){ values.put("seckey" , user.getSeckey()); }
        if(user.getType() > 0){ values.put("type" , user.getType()); }
        db.insert("chat_user" , null , values);
        return true;
    }



    /**
     * @chat_user表
     * TODO:根据uid获取用户信息
     * @param uid 用户uid
     * @return 返回用户信息，查询为空返回null
     */
    public static DBUser get_oneuser(int uid){
        if(dbHelper == null) return null;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        if(db == null) return null;

        //查询数据
        Cursor cursor = db.query(
                "chat_user" ,
                new String[]{"uid","username","headimg","pubkeya","prikeya","pubkeyb","prikeyb","seckey","type"} ,
                "uid=?" ,
                new String[]{String.valueOf(uid)} ,
                null ,
                null ,
                null ,
                null);
        if(cursor.moveToFirst()){
            cursor.move(0);
            DBUser user = new DBUser();
            user.setUid(cursor.getInt(0));
            user.setName(cursor.getString(1));
            user.setHeadimg(cursor.getString(2));
            user.setPubkeya(cursor.getString(3));
            user.setPrikeya(cursor.getString(4));
            user.setPubkeyb(cursor.getString(5));
            user.setPrikeyb(cursor.getString(6));
            user.setSeckey(cursor.getString(7));
            user.setType(cursor.getInt(8));
            cursor.close();
            return user;
        }
        cursor.close();
        return null;
    }

    /**
     * @chat_user表
     * TODO:获取新的朋友申请列表
     * @return users列表，没有数据返回null
     */
    public static List<DBUser> get_newfrienduser(){
        if(dbHelper == null) return null;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        if(db == null) return null;

        //查询数据
        Cursor cursor = db.query(
                "chat_user" ,
                new String[]{"uid","username","headimg","pubkeya","prikeya","pubkeyb","prikeyb","seckey","type"} ,
                "type=? OR type=? OR type=?" ,
                new String[]{String.valueOf(3) , String.valueOf(4), String.valueOf(5)} ,
                null ,
                null ,
                "id DESC" ,
                "20");
        if(cursor.moveToFirst()){
            List<DBUser> users = new ArrayList<DBUser>();
            do {
                DBUser user = new DBUser();
                user.setUid(cursor.getInt(0));
                user.setName(cursor.getString(1));
                user.setHeadimg(cursor.getString(2));
                user.setPubkeya(cursor.getString(3));
                user.setPrikeya(cursor.getString(4));
                user.setPubkeyb(cursor.getString(5));
                user.setPrikeyb(cursor.getString(6));
                user.setSeckey(cursor.getString(7));
                user.setType(cursor.getInt(8));
                users.add(user);
            }while (cursor.moveToNext());
            cursor.close();
            return users;
        }
        cursor.close();
        return null;
    }

    /**
     * @chat_session表
     * TODO:获取chat_session表中所有数据
     * @return sessions列表，没有数据返回null
     */
    public static List<DBSession> get_allsessions(){
        if(dbHelper == null) return null;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        if(db == null) return null;
        //查询数据
        Cursor cursor = db.query(
                "chat_session" ,
                new String[]{"uid","username","headimg","msgtype","lastmsg","lasttime","unread"} ,
                null ,
                null ,
                null ,
                null ,
                null ,
                null);
        if(cursor.moveToFirst()){
            List<DBSession> sessions = new ArrayList<DBSession>();
            do {
                DBSession session = new DBSession();
                session.setUid(cursor.getInt(0));
                session.setName(cursor.getString(1));
                session.setHeadimg(cursor.getString(2));
                session.setMsgtype(cursor.getInt(3));
                session.setLastmsg(cursor.getString(4));
                session.setLasttime(cursor.getString(5));
                session.setUnread(cursor.getInt(6));
                sessions.add(session);
            }while (cursor.moveToNext());
            cursor.close();
            return sessions;
        }
        cursor.close();
        return null;
    }

    /**
     * @TODO:删除chat_session表中的会话记录
     * @param uid 用户uid
     * @return  结果（true-成功；false-失败）
     */
    public static boolean del_session(int uid){
        if(dbHelper == null) return false;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db == null) return false;
        if(uid <= 0) return false;
        db.delete("chat_session" , "uid=?" ,new String[]{String.valueOf(uid)});
        return true;
    }

    /**
     * @chat_session表
     * @TODO:根据uid获取一个会话
     * @param uid 用户yid
     * @return  会话信息类
     */
    public static DBSession get_onesession(int uid){
        if(dbHelper == null) return null;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        if(db == null) return null;

        //查询数据
        Cursor cursor = db.query(
                "chat_session" ,
                new String[]{"uid","username","headimg","msgtype","lastmsg","lasttime","unread"} ,
                "uid=?" ,
                new String[]{String.valueOf(uid)} ,
                null ,
                null ,
                null ,
                null);
        if(cursor.moveToFirst()){
            cursor.move(0);
            DBSession session = new DBSession();
            session.setUid(cursor.getInt(0));
            session.setName(cursor.getString(1));
            session.setHeadimg(cursor.getString(2));
            session.setMsgtype(cursor.getInt(3));
            session.setLastmsg(cursor.getString(4));
            session.setLasttime(cursor.getString(5));
            session.setUnread(cursor.getInt(6));
            cursor.close();
            return session;
        }
        cursor.close();
        return null;
    }

    /**
      * @chat_session表
      * TODO:修改会话信息表
      * @param session 要修改的会话信息类
      * @return  结果（true-成功；false-失败）
     */
    public static boolean update_session(DBSession session){
        if(dbHelper == null) return false;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db == null) return false;
        if(session.getUid() <= 0) return false;
        ContentValues values = new ContentValues();
        if(session.getName() != null){ values.put("username" , session.getName()); }
        if(session.getHeadimg() != null){ values.put("headimg" , session.getHeadimg()); }
        if(session.getMsgtype() > 0){ values.put("msgtype" , session.getMsgtype()); }
        if(session.getLastmsg() != null){ values.put("lastmsg" , session.getLastmsg()); }
        if(session.getLasttime() != null){ values.put("lasttime" , session.getLasttime()); }
        if(session.getUnread() >= 0){ values.put("unread" , session.getUnread()); }
        db.update("chat_session" ,  values , "uid=?" ,new String[]{String.valueOf(session.getUid())});
        return true;
    }

    /**
     * @chat_session表
     * TODO:新建会话信息表,如果存在则覆盖
     * @param session
     * @return
     */
    public static boolean insert_session(DBSession session){
        if(dbHelper == null) return false;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db == null) return false;
        if(session.getUid() <= 0) return false;
        db.delete("chat_session" , "uid=?" ,new String[]{String.valueOf(session.getUid())});    //如果有删除相关数据
        ContentValues values = new ContentValues();
        values.put("uid" , session.getUid());
        if(session.getName() != null){ values.put("username" , session.getName()); }
        if(session.getHeadimg() != null){ values.put("headimg" , session.getHeadimg()); }
        if(session.getMsgtype() > 0){ values.put("msgtype" , session.getMsgtype()); }
        if(session.getLastmsg() != null){ values.put("lastmsg" , session.getLastmsg()); }
        if(session.getLasttime() != null){ values.put("lasttime" , session.getLasttime()); }
        if(session.getUnread() >= 0){ values.put("unread" , session.getUnread()); }
        db.insert("chat_session" , null , values);
        return true;
    }
}
